import { createSlice } from "@reduxjs/toolkit";
import { useSelector } from "react-redux";
import { getUserInfo, postLogin, postLogout } from "@/api/auth";

// 创建auth切片
const authSlice = createSlice({
    name: "auth",
    initialState: {
        // token
        token: localStorage.getItem("token") || "",
        // 用户信息
        userInfo: localStorage.getItem("userInfo") || {},
    },
    reducers: {
        // 更新token
        upToken(state: any, { payload }: any) {
            state.token = localStorage.token = payload;
        },
        // 更新用户信息
        upUserInfo(state: any, { payload }: any) {
            state.userInfo = localStorage.userInfo = payload;
        },
        // 清除本地和状态中的token和userInfo
        clearState(state: any, { payload }: any) {
            localStorage.clear();
            state.token = payload;
            state.userInfo = {};
        },
    },
});

// 暴露登录更新token的action
const { upToken } = authSlice.actions;
// 登录的异步action
export const postLoginAsync = function (values: any) {
    return async (dispatch: any) => {
        const result = await postLogin(values);
        console.log(result);
        dispatch(upToken(result.data));
        return result;
    };
};

// 暴露更新用户信息的action
const { upUserInfo } = authSlice.actions;
// 获取用户信息的异步action
export const getUserInfoAsync = function () {
    return async (dispatch: any, getState: any) => {
        // 如果已经获取过用户信息，就不再获取
        const state = getState();
        if (state.auth.userInfo.name) return;
        const result = await getUserInfo();
        dispatch(
            upUserInfo({
                name: result.data.name,
                avatar: result.data.avatar,
            })
        );
    };
};

// 暴露清除token和userInfo的action
const { clearState } = authSlice.actions;
// 退出登录的异步action
export const logoutAsync = function () {
    return async (dispatch: any) => {
        await postLogout();
        dispatch(clearState(null));
    };
};

// 暴露封装的获取状态的方法
export const useSelectorAuth = () => useSelector((state: any) => state.auth);
export default authSlice.reducer;
